import 'package:flutter/material.dart' show debugPrint;
import 'package:hive/hive.dart';

import '../index.dart';

class CommentService {
  static const String _boxName = 'comments';

  static Future<void> initialize() async {
    // 注册适配器（必须在打开box之前）
    if (!Hive.isAdapterRegistered(2)) {
      Hive.registerAdapter(CommentEntityAdapter());
    }

    // 打开comments数据盒子
    await Hive.openBox<CommentEntity>(_boxName);

    // 初始化默认评论数据
    await _initializeDefaultComments();
  }

  static Future<void> _initializeDefaultComments() async {
    final box = Hive.box<CommentEntity>(_boxName);

    // 如果数据库为空，添加默认评论
    if (box.isEmpty) {
      for (final comment in sampleComments) {
        await box.put(comment.id, comment);
      }
    }
  }

  // 根据分享ID获取评论列表
  static Future<List<CommentEntity>> getCommentsByShareId(
    String shareId,
  ) async {
    final box = Hive.box<CommentEntity>(_boxName);

    // 首先获取分享信息
    final shares = await ShareService.getSharesById(shareId);
    if (shares.isEmpty) {
      return [];
    }

    final share = shares.first;
    final commentIds = share.commentIds;

    // 根据评论ID列表获取评论
    final comments = <CommentEntity>[];
    for (final commentId in commentIds) {
      final comment = box.get(commentId);
      if (comment != null) {
        comments.add(comment);
      }
    }

    return comments;
  }

  // 添加新评论
  static Future<bool> addComment(CommentEntity comment, String shareId) async {
    debugPrint('addComment: $comment');
    debugPrint('shareId: $shareId');

    try {
      final commentBox = Hive.box<CommentEntity>(_boxName);
      await commentBox.put(comment.id, comment);

      // 同时更新分享的commentIds列表
      final shareBox = Hive.box<ShareEntity>('shares');
      final share = shareBox.get(shareId);
      if (share != null) {
        final updatedCommentIds = List<String>.from(share.commentIds);
        updatedCommentIds.add(comment.id);

        final updatedShare = ShareEntity(
          id: share.id,
          description: share.description,
          image: share.image,
          emotion: share.emotion,
          date: share.date,
          commentIds: updatedCommentIds,
          browses: share.browses,
          video: share.video, 
        );

        await shareBox.put(shareId, updatedShare);
      }

      return true;
    } catch (e) {
      debugPrint('添加评论失败: $e');
      return false;
    }
  }
}
